use std::{env, fs::File, io::BufReader, path::Path};
use tauri::{api, AppHandle, Manager, Window};

#[tauri::command]
pub async fn getenv(name: String) -> String {
  env::var(name).unwrap_or("".to_string())
}

// 判断文件是否存在
#[tauri::command]
pub async fn exists(path: String) -> bool {
  // Path::new(&path[..]).exists()
  Path::new(path.clone().to_owned().as_str()).exists()
}

fn get_manifest_content(path: &str) -> Result<serde_json::Value, String> {
  // Open the file in read-only mode with buffer.
  let manifest = Path::new(path).join("manifest.json");
  let file = File::open(manifest).map_err(|e| e.to_string())?;
  let reader = BufReader::new(file);
  // Read the JSON contents of the file as an instance of `User`.
  let value = serde_json::from_reader(reader).map_err(|e| e.to_string())?;
  Ok(value)
}

#[tauri::command]
pub fn get_all_extensions(app: AppHandle) -> Result<serde_json::Value, String> {
  let extensions_dir = api::path::resolve_path(
    &app.config(),
    app.package_info(),
    &app.env(),
    "extensions",
    Some(api::path::BaseDirectory::Resource),
  )
  .unwrap();
  let mut values: Vec<serde_json::Value> = vec![];
  for entry in extensions_dir.read_dir().expect("read_dir call failed") {
    if let Ok(entry) = entry {
      if entry.path().is_file() {
        continue;
      }
      let manifest_file = entry
        .path()
        .join("manifest.json")
        .to_str()
        .unwrap()
        .to_string();
      if let Ok(file) = File::open(manifest_file) {
        let reader = BufReader::new(file);
        let value = serde_json::from_reader(reader).map_err(|e| e.to_string())?;
        values.push(value);
      };
    }
  }
  Ok(serde_json::Value::Array(values))
}

#[tauri::command]
pub fn open_devtools(window: Window) {
  window.open_devtools();
}

//
#[tauri::command]
pub async fn get_manifest(path: &str) -> Result<serde_json::Value, String> {
  match get_manifest_content(path) {
    Err(err) => Err(err.to_string()),
    Ok(value) => Ok(value),
  }
}
